# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

# A list of supported languages

ENV["LC_ALL"] = "de_DE.UTF-8"
ENV["LANG"] = "de_DE.UTF-8"

ENV["FASTLANE_SKIP_UPDATE_CHECK"] = "true"
ENV['ITMSTRANSPORTER_FORCE_ITMS_PACKAGE_UPLOAD'] = 'true'

default_platform(:ios)

platform :ios do

### PRE-LANE ACTIONS ############################

  before_all do
    setup_circle_ci

    if is_ci
      xcode_select("/Applications/Xcode_13_4_1.app") # Uncommented until we are self hosted 100%
      xcversion(version: "~> 13.4.1")
    end
  end

### LANES #######################################

  desc "Update license file"
  lane :update_licenses do
    update_third_party_notice()
  end

  desc "Build project for testing"
  lane :build_for_testing do
    # build only, no tests
    run_tests(
      build_for_testing: true,
      output_xctestrun: true,
      clean: true,
      scheme: "ENA",
      reset_simulator: true,
      derived_data_path: "./DerivedData"
    )
  end

  desc "Runs unit tests without building"
  lane :test_without_building do | options |
    begin
      # Execute tests for given test plan
      testPlan = options[:testplan] || "AllTests"
      run_tests(
        scheme: "ENA",
        derived_data_path: "./DerivedData",
        test_without_building: true,
        testplan: testPlan,
        only_test_configurations: ["DE"],
        devices: ["iPhone 13"],
        skip_detect_devices: true,
        prelaunch_simulator: false,
        skip_package_dependencies_resolution: true,
        disable_package_automatic_updates: true,
        result_bundle: true,
        code_coverage: true,
        reset_simulator: true,
        concurrent_workers: 7, # 8 cores make 7 concurrent tests right? :D
        output_style: "raw", # prevents long periods of silence which makes the CI & devs nervous
        output_types: "",
        number_of_retries: 2
      )
    rescue
      UI.user_error!("Tests did fail, please check logs above or ENA.xcresult.zip")
    ensure
      trainer(
        output_directory: "fastlane/test_output/",
        path: "fastlane/test_output/",
        extension: ".junit",
        fail_build: false
      )

      zip(
        path: "fastlane/test_output/ENA.xcresult",
        output_path: "fastlane/test_output/ENA.xcresult.zip",
        verbose: false
      )
    end
  end

  desc "Build project (Community)"
  lane :build_community do
    build_ios_app(
      skip_codesigning: true,
      export_method: "ad-hoc",
      skip_package_ipa: true,
      scheme: "ENACommunity"
    )
  end

  desc "Lint code"
  lane :lint do
    swiftlint(
      executable: "swiftlint",
      mode: :lint,
      output_file: "swiftlint.html",
      config_file: "ENA/.swiftlint.yml",
      strict: true,
      quiet: true,
      no_cache: false,
      reporter: "html"
    )
  end

  desc "Create (localized) screenshots"
  lane :screenshot do |options|
    begin

     output_dir = "./screenshots/screenshots-#{options[:languages]}-#{options[:mode]}"

      capture_ios_screenshots(
        devices: ["iPhone 13"],
        scheme: "ENAScreenshots",
        testplan: "Screenshots",
        clear_previous_screenshots: true,
        erase_simulator: true,
        skip_helper_version_check: true,
        localize_simulator: true,
        disable_slide_to_type: true,
        languages: options[:languages],
        dark_mode: options[:mode] == "dark",
        output_directory: output_dir,
        result_bundle: true,
        skip_open_summary: true,
        derived_data_path: "./DerivedData",
        test_without_building: true,
        skip_package_dependencies_resolution: true,
        disable_package_automatic_updates: true,
        number_of_retries: 2
        )
    rescue
      UI.user_error!("Tests did fail, please check logs above or ENA.xcresult.zip")
    ensure
      trainer(
        output_directory: "fastlane/test_output/#{options[:languages]}-#{options[:mode]}",
        path: "#{output_dir}/test_output/#{options[:languages]}",
        extension: ".junit",
        fail_build: false
      )
      # no xcresult created, so no zip like in the other lanes
    end
  end

  desc "Build and upload for testing"
  lane :betaRelease do
    match(
      type: "appstore"
    )

    build_ios_app(
      scheme: "ENA",
      configuration: "TestFlight",
      clean: true
    )

    upload_to_testflight(
      username: "cwa.technical-user@sap.com",
      apple_id: "1515713549",
      itc_provider: "523TP53AQF",
      skip_waiting_for_build_processing: true,
      skip_submission: true,  # only upload
    )
  end

  desc "Ad hoc distribution"
  lane :adHocDistribution do
    match(
      type: "adhoc",
      app_identifier: "de.rki.coronawarnapp-dev",
      template_name: "Exposure Notification for 523TP53AQF (Distribution) iOS Dist ADHOC"
    )

    build_ios_app(
      scheme: "ENA",
      configuration: "AdHoc",
      export_method: "ad-hoc",
      export_options: {
        compileBitcode: false
      },
      clean: true
    )
    version = get_version_number(
      xcodeproj: "./ENA/ENA.xcodeproj",
      target: "ENA",
      configuration: "AdHoc"
    )
    build = get_build_number(
      xcodeproj: "./ENA/ENA.xcodeproj"
    )
    UI.success "The app version number is #{version}-RC#{build}"
    # Upload to Mobile Device Cloud
    sh("curl \
      --location \
      --request POST '#{ENV["TSI_CLOUD_URL"]}' \
      --header 'Authorization: Bearer #{ENV["TSI_CLOUD_TOKEN"]}' \
      --form 'file=@../ENA.ipa' \
      --form 'uniqueName=\"#{version}-RC#{build}\"'"
    )

    # Trigger Tests on Mobile Device Cloud via GitHub Action on Repo cwa-app-automation
    sh("
      curl \
      -X POST \
      -H 'Accept: application/vnd.github.v3+json' \
      -H 'authorization: Bearer #{ENV["GITHUB_ACCESS_TOKEN"]}' \
      -d '{\"ref\":\"main\"}' \
      https://api.github.com/repos/corona-warn-app/cwa-app-automation/actions/workflows/32065376/dispatches"
    )

    sh("
      curl \
      -X POST \
      -H 'Accept: application/vnd.github.v3+json' \
      -H 'authorization: Bearer #{ENV["GITHUB_ACCESS_TOKEN"]}' \
      -d '{\"ref\":\"main\"}' \
      https://api.github.com/repos/corona-warn-app/cwa-app-automation/actions/workflows/32065377/dispatches"
    )

  end

  desc "Update GitHub Pages"
  lane :updateDocs do

    # Create docs
    jazzy(
     config: ".jazzy.yaml"
    )

    # Deploy to gh pages
    sh("npm install -g --silent gh-pages@2.0.1")
    sh("gh-pages --message \"[ci skip] Update docs\" --dist ../../../docs/swift-doc")

  end

end
